﻿#include "LocaleEditEntry.h"
#include "EnumEditEntry.h"

struct LocaleEditEntry::LocaleEditEntryPrivate {
    QPointer<EnumEditEntry> entryCountry;
    QPointer<EnumEditEntry> entryLanguage;
};

LocaleEditEntry::~LocaleEditEntry() { }

LocaleEditEntry::LocaleEditEntry(QWidget *parent) : StringEditEntry {parent} {
    p.reset(new LocaleEditEntryPrivate);
    initUi();
    retranslateLanguage();
}

void LocaleEditEntry::setValue(const QLocale &locale) {
    const auto &languageString = QLocale::languageToString(locale.language());
    const auto &countryString = QLocale::countryToString(locale.country());
    const auto &text = QString("%1, %2").arg(languageString).arg(countryString);
    StringEditEntry::setValue(text);

    p->entryLanguage->setValue(locale.language());
    p->entryCountry->setValue(locale.country());
}

QLocale LocaleEditEntry::value() const {
    const auto language = QLocale::Language(p->entryLanguage->value());
    const auto country = QLocale::Country(p->entryCountry->value());
    return QLocale(language, country);
}

void LocaleEditEntry::initUi() {
    p->entryLanguage = new EnumEditEntry;
    p->entryLanguage->setMetaEnum(QMetaEnum::fromType<QLocale::Language>());
    appendChildEntry(p->entryLanguage);
    connect(p->entryLanguage, &EnumEditEntry::valueChanged, [=]{
        emit valueChanged(value());
    });

    p->entryCountry = new EnumEditEntry;
    p->entryCountry->setMetaEnum(QMetaEnum::fromType<QLocale::Country>());
    appendChildEntry(p->entryCountry);
    connect(p->entryCountry, &EnumEditEntry::valueChanged, [=]{
        emit valueChanged(value());
    });
}

void LocaleEditEntry::retranslateLanguage() {
    p->entryLanguage->setTitle(tr("language"));
    p->entryCountry->setTitle(tr("country"));

}
